<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="预计结算时间" prop="queryDate">
              <el-date-picker
                clearable
                v-model="queryParams.queryDate"
                type="month"
                format="YYYY 年 MM 月"
                value-format="YYYY-MM-DD"
                placeholder="请选择结算时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Search" @click="openCollageAccountDialog">查询拼团账单</el-button>
          </el-col>
        </el-row>
      </template>
      <el-tabs type="card" v-model="queryParams.queryStatus" @tab-change="handleQuery">
        <el-tab-pane label="未结算" name="0"/>
        <el-tab-pane label="已结算" name="1"/>
      </el-tabs>
      <el-table border v-loading="loading" :data="collageAccountLogList">
        <el-table-column label="预计结算时间" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.finalTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品总金额" align="center" prop="totalPrice" />
        <el-table-column label="销售总金额" align="center" prop="saleTotalPrice" />
        <el-table-column label="优惠活动信息" align="center">
          <template #default="scope">
            <div>
              店铺优惠券金额：{{scope.row.shopDiscountsTotalMoney}}
            </div>
            <div style="margin-top: 5px">
              平台优惠券金额：{{scope.row.officialDiscountsTotalMoney}}
            </div>
            <div style="margin-top: 5px">
              满减活动金额：{{scope.row.fullSubtractTotalMoney}}
            </div>
            <div style="margin-top: 5px">
              首单优惠活动金额：{{scope.row.firtstDiscountsTotalMoney}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手续费总金额" align="center" prop="totalServiceMoney" />
        <el-table-column align="center">
          <template #header>
            手续费减免 / 补缴金额
            <el-popover
              placement="top-start"
              title="提示"
              :width="400"
              trigger="hover"
              content="若拼团中存在使用过平台优惠券的订单,该部分优惠金额将会积累,用于减免本拼团或后续拼团的手续费">
              <template #reference>
                <el-icon><QuestionFilled /></el-icon>
              </template>
            </el-popover>
          </template>
          <template #default="scope">
            <div>
              减免金额：{{scope.row.reductionServiceMoney}}
            </div>
            <div>
              补缴金额：{{scope.row.compensationMoney}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="实收手续费总金额" align="center" prop="realityTotalServiceMoney" />
        <el-table-column label="合计" align="center">
          <template #default="scope">
            <div>
              <span style="color: dodgerblue">销售总金额：{{scope.row.saleTotalPrice}}</span>
            </div>
            <div>
              -
            </div>
            <div>
              <span style="color: orange">实收手续费总金额：{{scope.row.realityTotalServiceMoney}}</span>
            </div>
            <div>
              =
            </div>
            <div>
              <span style="color: red; font-weight: bolder">实际到账金额：{{scope.row.realityIntoMoney}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" @click="handleUpdate(scope.row)">详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

    </el-card>
    <!-- 添加或修改拼团结算账单记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="95%" append-to-body>
      <el-table border v-loading="loading" :data="collageAccountDetailList">
        <el-table-column label="拼团信息" align="center">
          <template #default="scope">
            <div class="common-flex-image" v-if="scope.row.cardCollageVo">
              <image-preview :src="scope.row.cardCollageVo.imagePath" :width="100" :height="100"/>
              <div style="width: 250px; margin-left: 20px;" align="left">
                <div>
                  名称：{{scope.row.cardCollageVo.collageName}}
                </div>
                <div style="margin-top: 5px">
                  编号：{{scope.row.cardCollageVo.collageCode}}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" align="center">
          <template #default="scope">
            <div>
              商品金额：{{scope.row.totalPrice}}
            </div>
            <div style="margin-top: 5px">
              销售金额：{{scope.row.saleTotalPrice}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="优惠活动信息" align="center">
          <template #default="scope">
            <div>
              店铺优惠券金额：{{scope.row.shopDiscountsTotalMoney}}
            </div>
            <div style="margin-top: 5px">
              平台优惠券金额：{{scope.row.officialDiscountsTotalMoney}}
            </div>
            <div style="margin-top: 5px">
              满减活动金额：{{scope.row.fullSubtractTotalMoney}}
            </div>
            <div style="margin-top: 5px">
              首单优惠活动金额：{{scope.row.firtstDiscountsTotalMoney}}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            手续费信息
            <el-popover
              placement="top-start"
              title="提示"
              :width="400"
              trigger="hover"
              content="若拼团中存在使用过平台优惠券的订单,该部分优惠金额将会积累,用于减免本拼团或后续拼团的手续费">
              <template #reference>
                <el-icon><QuestionFilled /></el-icon>
              </template>
            </el-popover>
          </template>
          <template #default="scope">
            <div>
              手续费金额：{{scope.row.totalServiceMoney}}
            </div>
            <div style="margin-top: 5px">
              手续费减免金额：{{scope.row.reductionServiceMoney}}
            </div>
            <div style="margin-top: 5px">
              手续费补缴金额：{{scope.row.compensationMoney}}
            </div>
            <div style="margin-top: 5px">
              实收手续费总金额：{{scope.row.realityTotalServiceMoney}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center">
          <template #default="scope">
            <div>
              <span style="color: dodgerblue">销售总金额：{{scope.row.saleTotalPrice}}</span>
            </div>
            <div>
              -
            </div>
            <div>
              <span style="color: orange">实收手续费总金额：{{scope.row.realityTotalServiceMoney}}</span>
            </div>
            <div>
              =
            </div>
            <div>
              <span style="color: red; font-weight: bolder">实际到账金额：{{scope.row.realityIntoMoney}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="子账单信息" align="center" width="500px">
          <template #default="scope">
            <el-card v-for="(cardCollageAccountDetailLog, index) in scope.row.cardCollageAccountDetailLogList" :key="index" style="margin-bottom: 5px">
              <template #header>
                <div class="card-header">
                  <el-row>
                    <el-col :span="12" align="left">
                      <dict-tag :options="collage_account_detail_type" :value="cardCollageAccountDetailLog.detailType" />
                    </el-col>
                    <el-col :span="6">
                      <el-link type="primary" @click="openOrderDialog(scope.row.cardCollageVo, cardCollageAccountDetailLog)">订单信息</el-link>
                    </el-col>
                    <el-col :span="6" align="right">
                      <el-popover
                        placement="top-start"
                        title="明细"
                        :width="1000"
                        trigger="hover">
                        <template #reference>
                          <el-link type="primary">明细</el-link>
                        </template>
                        <el-descriptions
                          direction="vertical"
                          :column="6"
                          border>
                          <el-descriptions-item label="商品金额">{{cardCollageAccountDetailLog.totalPrice}}</el-descriptions-item>
                          <el-descriptions-item label="销售金额">{{cardCollageAccountDetailLog.saleTotalPrice}}</el-descriptions-item>
                          <el-descriptions-item label="店铺优惠券金额">{{cardCollageAccountDetailLog.shopDiscountsTotalMoney}}</el-descriptions-item>
                          <el-descriptions-item label="平台优惠券金额">{{cardCollageAccountDetailLog.officialDiscountsTotalMoney}}</el-descriptions-item>
                          <el-descriptions-item label="满减活动金额">{{cardCollageAccountDetailLog.fullSubtractTotalMoney}}</el-descriptions-item>
                          <el-descriptions-item label="首单优惠活动金额">{{cardCollageAccountDetailLog.firtstDiscountsTotalMoney}}</el-descriptions-item>
                          <el-descriptions-item label="手续费金额">{{cardCollageAccountDetailLog.totalServiceMoney}}</el-descriptions-item>
                          <el-descriptions-item label="手续费减免金额">{{cardCollageAccountDetailLog.reductionServiceMoney}}</el-descriptions-item>
                          <el-descriptions-item label="手续费补缴金额">{{cardCollageAccountDetailLog.compensationMoney}}</el-descriptions-item>
                          <el-descriptions-item label="实收手续费金额">{{cardCollageAccountDetailLog.realityTotalServiceMoney}}</el-descriptions-item>
                          <el-descriptions-item label="实际到账金额">{{cardCollageAccountDetailLog.realityIntoMoney}}</el-descriptions-item>
                        </el-descriptions>
                      </el-popover>
                    </el-col>
                  </el-row>
                </div>
              </template>
<!--              <div>-->
<!--                <dict-tag :options="online_remittance_account_type" :value="cardCollageAccountDetailLog.onlineType" />-->
<!--              </div>-->
              <div style="margin-top: 5px">
                销售金额：{{cardCollageAccountDetailLog.saleTotalPrice}}
              </div>
              <div style="margin-top: 5px">
                实收手续费总金额：{{cardCollageAccountDetailLog.realityTotalServiceMoney}}
              </div>
              <div style="margin-top: 5px">
                实际到账金额：{{cardCollageAccountDetailLog.realityIntoMoney}}
              </div>
            </el-card>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="detailQueryParams.pageNum" v-model:limit="detailQueryParams.pageSize" @pagination="queryDetail(detailQueryParams.queryDate)" />
    </el-dialog>

    <!-- 订单列表对话框 -->
    <el-dialog :title="orderDialog.title" v-model="orderDialog.visible" width="85%" append-to-body v-if="orderDialog.visible" destroy-on-close>
      <el-table border v-loading="loading" :data="orderList">
        <el-table-column label="订单编号" align="center" prop="cardOrderNumber"/>
        <el-table-column label="单价" align="center" prop="unitPrice" />
        <el-table-column label="购买数量" align="center" prop="count"/>
        <el-table-column label="订单总价" align="center" prop="orderAmount"/>
        <el-table-column label="优惠金额" align="center" prop="subtractMoney"/>
        <el-table-column label="实付金额" align="center" prop="actualPayment"/>
        <el-table-column label="服务费金额" align="center" prop="serviceMoney"/>
        <el-table-column label="实际到账金额" align="center" prop="realityIntoMoney" />
      </el-table>

      <pagination v-show="orderTotal > 0" :total="orderTotal" v-model:page="orderQueryParams.pageNum" v-model:limit="orderQueryParams.pageSize" @pagination="queryCollageAccountLogOrderListData(orderQueryParams.collageId, orderQueryParams.detailType)" />
    </el-dialog>

    <!-- 拼团账单对话框 -->
    <el-dialog :title="collageAccountDialog.title" v-model="collageAccountDialog.visible" width="80%" append-to-body v-if="collageAccountDialog.visible" destroy-on-close>
      <CollageAccount/>
    </el-dialog>
  </div>
</template>

<script setup name="CollageAccountLog" lang="ts">
import { listCollageAccountLog, queryCollageAccountLogDetailList, queryCollageAccountLogOrderList  } from '@/api/system/collageAccountLog';
import { CollageAccountLogVO, CollageAccountLogQuery, CollageAccountLogForm } from '@/api/system/collageAccountLog/types';
import { CollageAccountDetailLogVO } from '@/api/system/collageAccountDetailLog/types';
import { CardCollageVO } from '@/api/system/cardCollage/types';
import { OrderVO } from '@/api/system/order/types';
import CollageAccount from '@/views/system/collageAccountLog/collageAccount.vue';

import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { collage_account_detail_type, online_remittance_account_type } = toRefs<any>(proxy?.useDict('collage_account_detail_type', 'online_remittance_account_type'));

const collageAccountLogList = ref<CollageAccountLogVO[]>([]);
const collageAccountDetailList = ref<CollageAccountLogVO[]>([]);
const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const orderTotal = ref(0);

const queryFormRef = ref<ElFormInstance>();
const collageAccountLogFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const orderDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const collageAccountDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CollageAccountLogForm = {
  id: undefined,
  collageId: undefined,
  shopId: undefined,
  collageName: undefined,
  collageCode: undefined,
  collageImage: undefined,
  collageCreateTime: undefined,
  collageUpTime: undefined,
  collageEndTime: undefined,
  unitPrice: undefined,
  totalNumber: undefined,
  totalPrice: undefined,
  saleTotalPrice: undefined,
  officialDiscountsTotalMoney: undefined,
  shopDiscountsTotalMoney: undefined,
  fullSubtractTotalMoney: undefined,
  firtstDiscountsTotalMoney: undefined,
  payServiceMoney: undefined,
  platformServiceMoney: undefined,
  totalServiceMoney: undefined,
  realityIntoMoney: undefined,
  compensationMoney: undefined,
  orderTotalNumber: undefined,
  shareOrderTotalNumber: undefined,
  notShareOrderTotalNumber: undefined,
  remittanceDiscountsOrderTotalNumber: undefined,
  accountLogStatus: undefined,
  remittanceStatus: undefined,
}
const data = reactive<PageData<CollageAccountLogForm, CollageAccountLogQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryDate: parseTime(new Date()),
    queryStatus: '0',
  },
  rules: {}
});

const detailData = reactive({
  detailQueryParams: {
    pageNum: 1,
    pageSize: 10,
    queryDate: undefined,
    queryStatus: '0',
  },
});

const orderData = reactive({
  orderQueryParams: {
    pageNum: 1,
    pageSize: 10,
    collageId: undefined,
    detailType: undefined,
  },
});

const { queryParams, form, rules } = toRefs(data);
const { detailQueryParams } = toRefs(detailData);
const { orderQueryParams } = toRefs(orderData);


/** 查询拼团结算账单记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCollageAccountLog(queryParams.value);
  collageAccountLogList.value = res.data;
  // total.value = res.total;
  loading.value = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  collageAccountLogFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CollageAccountLogVO) => {
  reset();
  const res = await queryDetail(row.finalTime);
  dialog.visible = true;
  dialog.title = "【" + parseTime(row.finalTime, '{y}-{m}-{d}') + "】汇款单详情";
}

/**
 * 查询结算详情
 */
const queryDetail = async (finalTime?: string) => {
  detailQueryParams.value.queryStatus = queryParams.value.queryStatus;
  detailQueryParams.value.queryDate = finalTime;
  loading.value = true;
  const res = await queryCollageAccountLogDetailList(detailQueryParams.value);
  collageAccountDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/**
 * 打开订单列表对话框
 */
const openOrderDialog = (collageVo: CardCollageVO, detailLogVO: CollageAccountDetailLogVO) => {
  const detailTypeName = detailLogVO.detailType == '1'?'线上结算':'线下结算';
  orderDialog.title = "【" + collageVo.collageName + "】" + detailTypeName + " 订单列表";
  orderDialog.visible = true;
  queryCollageAccountLogOrderListData(detailLogVO.collageId, detailLogVO.detailType);
}

/**
 * 查询结算订单
 */
const queryCollageAccountLogOrderListData = async (collageId: any, detailType: string) => {
  orderQueryParams.value.collageId = collageId;
  orderQueryParams.value.detailType = detailType;
  loading.value = true;
  const res = await queryCollageAccountLogOrderList(orderQueryParams.value);
  orderList.value = res.rows;
  orderTotal.value = res.total;
  loading.value = false;
}

/**
 * 打开拼团汇款对话框
 */
const openCollageAccountDialog = () => {
  collageAccountDialog.title = "查询拼团账单";
  collageAccountDialog.visible = true;
}

onMounted(() => {
  getList();
});
</script>
